<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <GzSearchForm :searchFunc="searchFunc" :resetFunc="() => { searchData = {} }">
        <a-form-item class="table-search-item" label="机构号">  
          <a-input v-model:value="searchData['agentNo']" label="机构号" :placeholder="'机构号'" />
        </a-form-item>
        <a-form-item class="table-search-item" label="机构名称"> 
          <a-input v-model:value="searchData['agentName']" :placeholder="'机构名称'" />
        </a-form-item>
      </GzSearchForm>
      <!-- 列表渲染 -->
      <GzTable 
        ref="infoTable" 
        :init-data="true" 
        :dataSource="tableDataSource"
        :table-columns="tableColumns" 
        :search-data="searchData" 
        row-key="agentNo"
        :expandedRowKeys="expandedRowKeys"
        :tableLoading="tableLoading"
        :isPagination="false"
        @btnLoadClose="btnLoading = false"
        @handleTableExpand="handleTableExpand"
      >
        <template #topBtnSlot>
          <div
            style="
              display: flex;
              gap: 10px;
              align-items: center;
              margin-bottom: 10px;
            "
          >
            <a-button v-if="$access('ENT_PROXY_INFO_EXPT')" type="primary" :loading="exportLaoding" style="margin: 0" @click="exportProxyInfo">
              导出机构信息
            </a-button>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'agentName'">
            <b>{{ record.agentName }}</b>
          </template>

          <template v-if="column.key === 'level'">
            <span v-if="record.level === 1">省级</span>
            <span v-if="record.level === 2">市级</span>
            <span v-if="record.level === 3">区县</span>
            <span v-if="record.level === 4">网点</span>
          </template>

          <template v-if="column.key === 'jdwd'">
            <span v-if="record.lng">{{ record.lng }}</span>
            <span v-if="record.lat"> / {{ record.lat }}</span>
          </template>

          <template v-if="column.key === 'state'">
            <a-badge :status="record.state === 0 ? 'error' : 'processing'" :text="record.state === 0 ? '禁用' : '启用'" />
          </template>

          <template v-if="column.key === 'isNavigation'">
            <span>{{ record.isNavigation ==0 ?'否':'是' }}</span>
          </template>

          <template v-if="column.key === 'operation'">
            <!-- 操作列插槽 -->
            <GzTableColumns>
              <!-- <a-button v-if="$access('ENT_PROXY_RESET_PASSWORD')" type="link" @click="liteManage">管理我的小程序</a-button> -->
              <a-button v-if="$access('ENT_PROXY_INFO_CREATE_ACC') && record.isSuperAdminAccount==0" type="link" @click="generateAccount(record)">生成账号</a-button>
              <a-button v-if="$access('ENT_PROXY_INFO_RESET_PWD') && record.isSuperAdminAccount==1" type="link" @click="resetPassword(record)">重置密码</a-button>
              <a-button v-if="$access('ENT_PROXY_INFO_EDIT')" type="link" @click="updateProxyInfo(record)">修改机构信息</a-button>
            </GzTableColumns>
          </template>
        </template>
      </GzTable>
    </a-card>
    <!-- 营销程序管理 -->
    <MarketingManage ref="marketingManageRef" />
    <!-- 修改机构信息 -->
    <InfoAddOrEdit ref="infoAddOrEdit" :callback-func="searchFunc" />
  </page-header-wrapper>
</template>
<script setup lang="ts">
import {$apiAgentInfoList,$apiAgentInfoAutoAddUser,$apiAgentInfoPwdReset,$apiAgentInfoExport} from '@/api/proxy/ProxyList/index'
import { useRouter } from '@/utils/routerUtils'
import { ref, reactive, getCurrentInstance,nextTick } from 'vue'
import MarketingManage from './MarketingManage.vue'
import { useAgentStore } from '@/store/modules/agent'
import InfoAddOrEdit from './AddOrEdit.vue'

const infoTable = ref()
const marketingManageRef = ref()
const infoAddOrEdit = ref()

const { $access, $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

let tableColumns = reactive([
  { key: 'agentName', title: '机构名称', width: 200, fixed: 'left' },
  { key: 'agentNo', title: '机构号', dataIndex: 'agentNo', width: 140, minWidth: 140, maxWidth: 170 },
  { key: 'agentShortName', title: '简称', dataIndex: 'agentShortName', width: 70, minWidth: 70, maxWidth: 100 },
  { key: 'level', title: '等级', dataIndex: 'level', width: 70, minWidth: 70, maxWidth: 100 },
  { key: 'hierarchyPath', title: '路径', dataIndex: 'hierarchyPath', width: 140, minWidth: 140, maxWidth: 170 },
  { key: 'addr', title: '地址', dataIndex: 'addr', width: 140, minWidth: 140, maxWidth: 170 },
  { key: 'jdwd', title: '经 / 纬度', dataIndex: 'jdwd', width: 140, minWidth: 140, maxWidth: 170 },
  { key: 'isNavigation', title: '导航是否可见', dataIndex: 'isNavigation', width: 140, minWidth: 140, maxWidth: 170 },
  { key: 'bindAcounts', title: '已绑定账户数', dataIndex: 'bindAcounts', width: 140, minWidth: 140, maxWidth: 170 },
  { key: 'linkName', title: '联系人姓名', dataIndex: 'linkName', width: 140, minWidth: 140, maxWidth: 170 },
  { key: 'linkPhone', title: '联系人手机号', dataIndex: 'linkPhone', width: 140, minWidth: 140, maxWidth: 170 },
  { key: 'state', title: '状态', dataIndex: 'state', width: 100 },
  { key: 'createdAt', title: '创建日期', dataIndex: 'createdAt', width: 200, minWidth: 200, maxWidth: 230 },
  { key: 'operation', title: '操作', width: 320, fixed: 'right', align: 'center', minWidth: 320, maxWidth: 340  }
])

let btnLoading = ref(false)
const exportLaoding = ref(false)
let searchData = ref({})


// 导出机构信息
const exportProxyInfo = () =>{
  exportLaoding.value = true
  $apiAgentInfoExport(searchData.value).then(res=>{
    if(res.successUrl){
      exportLaoding.value = false
      $infoBox.message.success('导出成功')
      const successUrl = res.successUrl
      const link = document.createElement('a')
      link.href = successUrl
      link.download = 'filename.xlsx' // 设置下载文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }else{
      exportLaoding.value = false
      $infoBox.message.warn('此次没有结果')
    }
    
  })
}

// 生成账号
const generateAccount = (record) =>{
  if(record.linkPhone==''||record.linkName==null){
    $infoBox.message.warning('无联系人账号！')
    return false
  }
  $apiAgentInfoAutoAddUser({agentNo:record.agentNo}).then(res=>{
    $infoBox.message.success('生成成功')
  })
}
// 重置密码
const resetPassword = (record) =>{
  if(record.linkPhone==''||record.linkName==null){
    $infoBox.message.warning('无联系人账号！')
    return false
  }
  // 确认重置密码
    $infoBox.confirmDanger('确认重置密码', '是否确认重置机构的密码？', () => {
      $apiAgentInfoPwdReset({agentNo:record.agentNo}).then(res => {
        $infoBox.message.success('重置成功')
      })
    })

}

// 修改机构信息
const updateProxyInfo = (record) =>{
    // 业务通用【修改】 函数
    infoAddOrEdit.value.show(record.agentNo)
}

/**
 * 点击【查询】按钮点击事件
 */
async function searchFunc() { 
  if(expandedRowKeys.value.length > 0){
    expandedRowKeys.value = []
  }
  // infoTable.value.refTable(true)
  // 如果searchData.value是个空对象或者对象值为空 则不请求数据
  if (Object.keys(searchData.value).length === 0 || Object.values(searchData.value).every(item => !item)) {
    initAgentList()
    return
  }
  tableLoading.value = true
  const agentList = await getAgentList({ ...searchData.value, pageSize: 200 })
  // 获取最小 level 值
  const minLevel = Math.min(...agentList.records.map(obj => obj.level))
  // 找到所有具有最小 level 值的对象
  const minObjects = agentList.records.filter(obj => obj.level === minLevel)
  // 为每个具有最小 level 值的对象添加 children 属性
  minObjects.forEach(obj => {
    obj.children = []
  })
  tableLoading.value = false
  tableDataSource.value = minObjects
}

/**
 * 营销程序管理
 */
function liteManage(){
 
  // marketingManageRef.value.show()
}

/**
 * 请求机构列表 pid 和 agentNo只需要传一个
 */
async function getAgentList(params) {
  return $apiAgentInfoList({ pageSize: 1, pageNumber: 1, ...params })
}

// 表格数据
const tableDataSource = ref([])
const tableLoading = ref(true)

// 初始化机构列表
async function initAgentList() {
  tableLoading.value = true
  const agentList = await getAgentList({ agentNo: useAgentStore().proxyListAgentNo })
  tableLoading.value = false
  agentList.records[0].children = []
  tableDataSource.value = agentList.records
}
initAgentList()

// 展开行
const expandedRowKeys = ref<string[]>([])
/**
 * 展开行事件
 */
function handleTableExpand(expanded:any, record:any) {
  if (expanded) {
    expandedRowKeys.value.push(record.agentNo)
    if(record.children.length === 0){
      tableLoading.value = true
      getAgentList({ pid: record.agentNo, pageSize: 200 }).then(res => {
        if(record.level !== 3){
          record.children = res.records.map(item => ({ ...item, children: [] }))
        }else{
          record.children = res.records
        }
        tableLoading.value = false
      })
    }
  }else{
    expandedRowKeys.value = expandedRowKeys.value.filter(item => item !== record.agentNo)
  }
}


</script>
